package com.liyunhan.SortAlgorithm;

import java.util.ArrayList;

/**
 * @Description: 冒泡排序
 * @Author: Liyunhan
 * @Date: 2021/10/3 21:27
 */
public class BubbleSort extends AlgorithmAbs {

    /**
     * 构造器
     * @param arrayList
     */
    public BubbleSort(ArrayList<Double> arrayList) {
        super(arrayList);
    }

    /**
     * 算法执行
     */
    @Override
    public void executeAlgorithm(int...ints) {
        boolean flag;

        for (int i = 0; i < arrayList.size() - 1; i++) {
            flag = false;

            for (int j = 0; j < arrayList.size() - 1 - i; j++) {
                if (arrayList.get(j) > arrayList.get(j + 1)) {
                    double temp = arrayList.get(j);
                    arrayList.set(j, arrayList.get(j + 1));
                    arrayList.set(j + 1, temp);
                    //有元素交换, flag设为true
                    flag = true;
                }
            }

            //冒泡排序的停止迭代条件是某一轮循环没有元素交换
            if (!flag) break;
        }
    }
}
